package com.kx.center.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kx.center.auth.Authentication;
import com.kx.center.entity.DailyCounting;
import com.kx.center.entity.DailyCountingDetail;
import com.kx.center.entity.query.QueryDailyCounting;
import com.kx.center.entity.query.QueryResult;
import com.kx.center.enumerate.MessageCode;
import com.kx.center.service.CountingService;
import com.kx.center.util.DateUtil;
import com.kx.center.util.JSONParser;
import com.kx.center.util.Response;

@Controller
@RequestMapping("/counting")
public class CountingController {

	@Autowired
	CountingService service;

	@RequestMapping(value = "daily/list/{storeId}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String daily_counting_list(HttpServletRequest request, @PathVariable("storeId") Integer storeId)
			throws Exception {
		
		Integer page, pageSize, status;
		Date from = null, to = null;

		QueryDailyCounting query = new QueryDailyCounting();

		String storeIdStr = request.getParameter("store");
		String fromStr = request.getParameter("from");
		String toStr = request.getParameter("to");
		
		String sortBy = request.getParameter("sortBy");
		String sortMethod = request.getParameter("sortMethod");
		
		status = NumberUtils.toInt(request.getParameter("status"));
		page = NumberUtils.toInt(request.getParameter("page"));
		pageSize = NumberUtils.toInt(request.getParameter("pageSize"));
		
		if(DateUtil.isDate(fromStr))
			from = DateUtils.parseDate(fromStr, "yyyy-MM-dd");

		if(DateUtil.isDate(toStr))
			to = DateUtils.parseDate(toStr + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
		
		if(storeId <= 0)
			storeId = NumberUtils.toInt(storeIdStr);
		
		if(StringUtils.isBlank(sortBy))
			sortBy = "addtime";
		
		if(StringUtils.isBlank(sortMethod))
			sortMethod = "desc";

		query.setFrom(from);
		query.setTo(to);
		query.setStoreId(storeId);
		query.setStatus(status);
		query.setPage(page);
		query.setPageSize(pageSize);
		query.setSortBy(sortBy);
		query.setSortMethod(sortMethod);

		if (storeId > 0) {
			query.setStoreId(storeId);
		}
		
		query.setSortBy("addtime");
		query.setSortMethod("desc");

		QueryResult result = service.queryDailyCounting(query);

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("page", result.getPage());
		map.put("pageSize", result.getPageSize());
		map.put("totalRecord", result.getTotalRecord());
		map.put("data", result.getData());

		return Response.success(map);
	}

	@RequestMapping(value = "daily/detail/{dcid}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String daily_counting_detail(HttpServletRequest request, @PathVariable("dcid") Integer dcid)
			throws Exception {
		if (dcid != null && dcid > 0) {
			List<DailyCountingDetail> list = service.findDailyCountingDetailByDCId(dcid);

			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("data", list);
			return Response.success(map);
		} else {
			return Response.error(MessageCode.NO_DATA);
		}
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "daily/save", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String save_daily_counting(HttpServletRequest request) {

		/*
		 * 名称: 日结盘点 地址: /api/counting/daily 输入: [{goods_id:1, goods_sku:
		 * 'xx0001', storage: 123},{goods_id:2, goods_sku: 'xx0002', storage:
		 * 123}] 返回: {status: 'ok', msg: ''} 出错返回: {status: 'error', code:
		 * 100001, msg: '发生错误'}
		 */

		String storeIdStr = request.getParameter("store_id");
		String dcIdStr = request.getParameter("daily_counting_id");

		String json = request.getParameter("data");

		if (NumberUtils.isDigits(storeIdStr) || NumberUtils.isDigits(dcIdStr)) {
			Integer storeId = NumberUtils.toInt(storeIdStr);
			Integer dcId = NumberUtils.toInt(dcIdStr);

			if (StringUtils.isBlank(json)) {
				return Response.error(MessageCode.JSON_WRONG);
			}

			ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();

			try {
				data = (ArrayList<HashMap<String, Object>>) JSONParser.parse(json, data.getClass());
			} catch (Exception e) {
				e.printStackTrace();
				return Response.error(MessageCode.JSON_WRONG);
			}

			DailyCounting counting = null;

			if (dcId > 0) {
				counting = service.findDailyCountingById(dcId);

				if (counting == null)
					return Response.error(MessageCode.DAILY_COUNTING_ID_WRONG);
			}

			service.saveDailyCounting(storeId, counting, data);

			return Response.success("盘点数据提交成功");
		} else {
			return Response.error(MessageCode.PARAMETER_WRONG);
		}
	}

	@RequestMapping(value = "daily/{id}/confirm", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String daily_counting_confirm(HttpServletRequest request, @PathVariable("id") Integer id) {

		if (id <= 0) {
			return Response.error(MessageCode.REQUEST_ERROR);
		} else {
			DailyCounting entity = service.findDailyCountingById(id);

			if (entity == null)
				return Response.error(MessageCode.DAILY_COUNTING_ID_WRONG);
			else {
				if (entity.getStatus() != 1)
					return Response.error(MessageCode.OPERATOR_FAIL);
				else {
					entity.setStatus(2);
					service.confirm(entity);
					return Response.success();
				}
			}
		}
	}

}
